package com.bw.home.ui

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bw.common.widget.NormalTitleBar
import com.bw.home.R
import com.bw.home.databinding.ActivitySearchBinding
import com.bw.home.databinding.ActivitySearchResultBinding
import com.bw.home.databinding.ItemSimplevideoBinding
import com.bw.home.intent.SimpleVideoKeywordIntent
import com.bw.home.model.entity.SimpleVideoEntity
import com.bw.home.model.service.SimpleVideoKeywordModel
import com.bw.home.state.SimpleVideoKeywordState
import com.bw.imageloader.ImageLoaderManager
import com.bw.mvicore.common.ConstantValue
import com.bw.mvicore.ui.BaseActivity
import com.bw.mvicore.ui.BaseMVIActivity

class SearchResultActivity : BaseMVIActivity() {
    private lateinit var viewModel:SimpleVideoKeywordModel
    private lateinit var adapter:SearchResultAdapter
    private var page:Int = 0
    private val pageSize:Int = 10
    private lateinit var keyword:String
    override fun generateModel() {
        viewModel=ViewModelProviders.of(this).get(SimpleVideoKeywordModel::class.java)
    }

    override fun releaseRes() {
    }

    private lateinit var binding:ActivitySearchResultBinding
    override fun generateContentView(): View {
        binding=  ActivitySearchResultBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        binding.rvHomeSearchresult.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
        adapter= SearchResultAdapter()
        binding.rvHomeSearchresult.adapter = adapter
    }

    override fun initData() {
        val bundle =  intent.getBundleExtra(ConstantValue.PARAMS)
        keyword = bundle?.getString("keyword")!!
        keyword.let {
            generateLifeCycleLaunch {
                viewModel.intents.send(SimpleVideoKeywordIntent.GetSimpleVideoByKeywordIntent(keyword!!,page,pageSize))
            }
        }

    }

    override fun initEvent() {
        binding.normalTitleBar.setTitle("搜索关键字：${keyword}")
        binding.normalTitleBar.setOnClickListener(object :NormalTitleBar.BackOnClickListener{
            override fun onClick() {
                closeThiz()
            }
        })
    }

    override fun handleState() {
       generateLifeCycleLaunch {
           viewModel.state.collect{
               when(it){
                   is SimpleVideoKeywordState.SimpleVideoKeywordDefaultState->{}
                   is SimpleVideoKeywordState.SimpleVideoKeywordSuccess->{
                        adapter.append(it.datas)
                   }
                   is SimpleVideoKeywordState.SimpleVideoKeywordFailed->{
                        showMsg("获取视频信息出错，info:${it.throwable.message}")
                   }
               }
           }
       }
    }

    class SearchResultAdapter:RecyclerView.Adapter<SearchResultAdapter.ViewHolder>(){
        private lateinit var mContext: Context
        class ViewHolder(view:View):RecyclerView.ViewHolder(view){
            val binding:ItemSimplevideoBinding by lazy {
                ItemSimplevideoBinding.bind(view)
            }
        }

        private var list:MutableList<SimpleVideoEntity> = mutableListOf()

        /**
         * 追加数据
         */
        fun append(_list:List<SimpleVideoEntity>){
            this.list.addAll(_list)
            this.notifyDataSetChanged()
        }

        /**
         * 刷新数据
         */
        fun refresh(_list:MutableList<SimpleVideoEntity>){
            this.list.clear()
            this.list.addAll(_list)
            this.notifyDataSetChanged()
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            this.mContext=parent.context
            val view =  LayoutInflater.from(parent.context).inflate(R.layout.item_simplevideo,parent,false)
            return ViewHolder(view)
        }

        override fun getItemCount(): Int {
            return this.list.size
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val videoData = this.list.get(position)
            holder.binding.tvHomeItemSimplevideoName.text = videoData.title
            holder.binding.tvHomeItemSimplevideoDescription.text = videoData.description
            ImageLoaderManager.getInstance().loadFileIntoImageView(this.mContext,videoData.avatar_url,holder.binding.ivHomeItemSimplevideoAuthorimg,null)
            ImageLoaderManager.getInstance().loadFileIntoImageView(this.mContext,videoData.videomainimag,holder.binding.ivHomeItemSimplevideoVideomainimg,null)
        }
    }
}